<template>
  <div class="page">
    <div class="page-panel" v-if="!part.isDelete" >
      <div class="page-panel-body">
        <!--<el-button type="primary" icon="el-icon-edit" @click="edit" :disabled="pending" v-if="allowEdit"> 编辑</el-button>-->
        <!--<el-button icon="el-icon-delete" @click="remove" :disabled="pending" v-if="allowEdit"> 删除</el-button>-->

        <el-button type="primary" @click="edit" :disabled="pending" v-if="allowEdit" v-track="getBtnsTrackData('TO_EDIT')">
          <i class="iconfont icon-edit-square"></i>
          {{$t('common.base.edit')}}
        </el-button>
        <el-button type="plain-third" @click="remove" :disabled="pending" v-if="allowDelete" v-track="getBtnsTrackData('DELETE')">
          <i class="iconfont icon-delete"></i>
          {{$t('common.base.delete')}}
        </el-button>

        <div class="pull-right">
          <!--<el-button type="primary" @click="record.dialog = true" :disabled="pending">添加备注</el-button>-->
          <el-button type="primary" @click="record.dialog = true" :disabled="pending" v-if="allowEdit" v-track="getBtnsTrackData('ADD_REMARKS')">{{$t('common.base.addRemark')}}</el-button>
        </div>
      </div>
    </div>
    <!-- 多列平铺效果 -->
    <div v-if="getLayout === 1" class="detail_h">
      <div class="detail">
        <BaseTileLayoutTabBar2
          :bar-list="mergeTabs"
          :now-item="currentTab.tabName"
          @changeItem="baseUpdate"
          @openLayoutModal="openBaseLayoutModal"
          class="layoutDialog2"
        ></BaseTileLayoutTabBar2>
        <div class="detail-layout">
          <el-tabs v-model="currentTab.tabName" @input="switchTab" @tab-click="rightTabClick">
            <el-tab-pane :label="$t('part.detail.text1')" name="leftInfo">
                  <!-- <sample-tooltip :row="part">
                  <template slot="content" slot-scope="{isContentTooltip}">
                    <div class="page-panel-head">
                      <h5>{{ $t('part.detail.text1') }}<span v-if="part.isDelete" class="part-delete">[{{ $t('common.base.deleted') }}]</span></h5>          
                    </div>
                   </template>
                  </sample-tooltip> -->
                <div class="page-panel-body bbx-cell-form-view">
                  <div :class="getformItem">
                    <div class="page-row  bbx-form-cell-item" :class="getformItemClass">
                      <div class="page-row-left">{{ $t('common.base.serialNumber') }}</div>
                      <div class="page-row-right">{{ part.serialNumber }}</div>
                    </div>
                    <div class="page-row bbx-form-cell-item" :class="getformItemClass">
                      <div class="page-row-left">{{ $t('common.base.name') }}</div>
                      <div class="page-row-right">{{ part.name }}</div>
                    </div>
                  <div class="page-row bbx-form-cell-item" :class="getformItemClass">
                    <div class="page-row-left">{{ $t('common.form.preview.serviceItem.colum3') }}</div>
                    <div class="page-row-right">{{ part.type }}</div>
                  </div>
                  <div class="page-row bbx-form-cell-item" :class="getformItemClass">
                    <div class="page-row-left">{{ $t('common.form.preview.sparepart.label3') }}</div>
                    <div class="page-row-right">{{ part.standard }}</div>
                  </div>
                  <div class="page-row bbx-form-cell-item" :class="getformItemClass">
                    <div class="page-row-left">{{ $t('common.form.preview.serviceItem.colum4') }}</div>
                    <div class="page-row-right">{{ part.unit }}</div>
                  </div>
                  <div v-if="serviceProviderShowPrice" class="page-row bbx-form-cell-item" :class="getformItemClass">
                    <div class="page-row-left">{{ $t('product.component.miniTable.partType.salePrice') }}</div>
                    <div class="page-row-right" v-if="part.id">{{ part.salePrice.toFixed(2) }}</div>
                  </div>
                  <div v-if="serviceProviderShowPrice" class="page-row bbx-form-cell-item" :class="getformItemClass">
                    <div class="page-row-left">{{ $t('product.component.miniTable.partType.costPrice') }}</div>
                    <div class="page-row-right" v-if="part.id">{{ part.costPrice.toFixed(2) }}</div>
                  </div>
                  <div class="page-row bbx-form-cell-item" :class="getformItemClass">
                    <div class="page-row-left">{{ $t('common.base.explain') }}</div>
                    <div class="page-row-right">{{ part.description }}</div>
                  </div>
                  <div class="page-row row-image bbx-form-cell-item" :class="getformItemClass">
                    <div class="page-row-left label-image">{{ $t('common.base.image') }}</div>
                    <div class="page-row-right content-image">
                      <template v-if="Array.isArray(part.imageGroup) && part.imageGroup.length > 0">
                        <base-file-item class="part-image-base" v-for="(item, index) in part.imageGroup" :source="part.imageGroup" :key="index" :file="item" readonly/>
                      </template>
                      <template v-else-if="Array.isArray(part.imageList) && part.imageList.length > 0">
                        <img class="part-image" style="padding: 5px" v-for="(img, idx) in part.imageList" :key="idx" :src="img" @click="preview(img, part.imageList)" :alt="$t('part.detail.text5')">
                      </template>
                      <template v-else-if="part.image">
                        <img class="part-image" :src="part.image" @click="preview(part.image)" :alt="$t('part.detail.text5')">
                      </template>
                    </div>
                  </div>
                  <div class="page-row bbx-form-cell-item" :class="getformItemClass">
                    <div class="page-row-left">{{ $t('common.base.status') }}</div>
                    <div class="page-row-right">{{ part.enable == 1 ? $t('common.base.enableState.0') : $t('common.base.enableState.1') }}</div>
                  </div>
                  <div class="page-row bbx-form-cell-item" :class="getformItemClass">
                    <div class="page-row-left">{{ $t('common.base.column.createTime') }}</div>
                    <div class="page-row-right">{{ part.createTime | fmt_datetime }}</div>
                  </div>
                  <div class="page-row bbx-form-cell-item" :class="getformItemClass">
                    <div class="page-row-left">{{ $t('product.detail.type.id') }}</div>
                    <div class="page-row-right">{{ part.id }}</div>
                  </div>
                  <div class="page-row productTypeField bbx-form-cell-item" :class="getformItemClass" v-if="initData && initData.openSuperCodePro">
                    <div class="page-row-left">{{ $t('common.form.type.related_catalog') }}</div>
                    <div class="page-row-right">
                      <div
                        :key="item.id"
                        v-for="item in productTypeField">
                        <el-tooltip
                          class="item"
                          effect="dark"
                          :content="item.pathName"
                          placement="top">
                          <p
                            class="link"
                            @click="openProductMenuTab(item.id)">
                            {{ item.pathName }}
                          </p>
                        </el-tooltip>
                      </div>
                    </div>
                  </div>
                </div>
                </div>
            </el-tab-pane>
            <el-tab-pane :label="$t('common.form.type.relatedData')">
               <span slot="label"><i class="el-icon-menu"></i> {{ $t('common.form.type.relatedData') }}</span>
            </el-tab-pane>
          
            <el-tab-pane :label="$t('common.base.dynamicInfo')" name="record">            
              <part-record :items="record.data.list"></part-record>

              <div class="part-record-loadmore" v-if="record.data.hasNextPage">
                <el-button type="text" :loading="record.loading" @click="loadMoreRecords">{{ record.loading ? $t('common.base.isLoading2') : $t('common.base.tip.loadMore') }}</el-button>
              </div>
            </el-tab-pane>
          
            <el-tab-pane :label="$t('common.base.usageRecord')" name="usageRecord" v-if="report && isAll">
              <div class="part-use-form">
                <div class="about-num">
                  <span>{{ $t('part.detail.text3') }}{{ usageRecord.data.taskTotalNum }}</span>
                  <span>{{ $t('part.detail.text4') }}{{ usageRecord.data.partTotalNum }}</span>
                </div>               
                <div class="part-use-form-group">
                  <!-- <div id="date-range" class="part-use-form-daterange">
                  <span>{{usageRecord.startTime}} - {{usageRecord.endTime}}</span> 
                  <b class="caret"></b>
                </div> -->
                  <date-picker @datePicker="datePicker" />
                </div>
              </div>
            
              <part-usage-record :page="usageRecord.data" @changePageNum="changePageNum"></part-usage-record>
            </el-tab-pane>
          
            <el-tab-pane :label="$t('part.detail.text6')" name="stock">
              <part-stock :stock="stock.data"></part-stock>
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>
    </div>
    <div class="page-main" v-if="getLayout === 2">
      <div class="page-panel page-main-detail" ref="detail" >
        <sample-tooltip :row="part">
          <template slot="content" slot-scope="{isContentTooltip}">
            <BaseTileLayoutTabBar2
            @openLayoutModal="openBaseLayoutModal"
            class="layoutDialog"
          ></BaseTileLayoutTabBar2>
            <div class="page-panel-head">
              <h5>{{$t('part.detail.text1')}}<span v-if="part.isDelete" class="part-delete">[{{$t('common.base.deleted')}}]</span></h5>          
            </div>
          </template>
        </sample-tooltip>
        <div class="page-panel-body">
          <div class="page-row">
            <div class="page-row-left">{{$t('common.base.serialNumber')}}</div>
            <div class="page-row-right">{{part.serialNumber}}</div>
          </div>
          <div class="page-row">
            <div class="page-row-left">{{$t('common.base.name')}}</div>
            <div class="page-row-right">{{part.name}}</div>
          </div>
          <div class="page-row">
            <div class="page-row-left">{{$t('common.form.preview.serviceItem.colum3')}}</div>
            <div class="page-row-right">{{part.type}}</div>
          </div>
          <div class="page-row">
            <div class="page-row-left">{{$t('common.form.preview.sparepart.label3')}}</div>
            <div class="page-row-right">{{part.standard}}</div>
          </div>
          <div class="page-row">
            <div class="page-row-left">{{$t('common.form.preview.serviceItem.colum4')}}</div>
            <div class="page-row-right">{{part.unit}}</div>
          </div>
          <div v-if="serviceProviderShowPrice" class="page-row">
            <div class="page-row-left">{{$t('product.component.miniTable.partType.salePrice')}}</div>
            <div class="page-row-right" v-if="part.id">{{part.salePrice.toFixed(2)}}</div>
          </div>
          <div v-if="serviceProviderShowPrice" class="page-row">
            <div class="page-row-left">{{$t('product.component.miniTable.partType.costPrice')}}</div>
            <div class="page-row-right" v-if="part.id">{{part.costPrice.toFixed(2)}}</div>
          </div>
          <div class="page-row">
            <div class="page-row-left">{{$t('common.base.explain')}}</div>
            <div class="page-row-right">{{part.description}}</div>
          </div>
          <div class="page-row row-image">
            <div class="page-row-left label-image">{{$t('common.base.image')}}</div>
            <div class="page-row-right content-image">
              <template v-if="Array.isArray(part.imageGroup) && part.imageGroup.length > 0">
                <base-file-item class="part-image-base" v-for="(item, index) in part.imageGroup" :source="part.imageGroup" :key="index" :file="item" readonly/>
              </template>
              <template v-else-if="Array.isArray(part.imageList) && part.imageList.length > 0">
                <img class="part-image" style="padding: 5px" v-for="(img, idx) in part.imageList" :key="idx" :src="img" @click="preview(img,part.imageList)" :alt="$t('part.detail.text5')">
              </template>
              <template v-else-if="part.image">
                <img class="part-image" :src="part.image" @click="preview(part.image)" :alt="$t('part.detail.text5')">
              </template>
            </div>
          </div>
          <div class="page-row">
            <div class="page-row-left">{{$t('common.base.status')}}</div>
            <div class="page-row-right">{{part.enable == 1 ? $t('common.base.enableState.0') : $t('common.base.enableState.1')}}</div>
          </div>
          <div class="page-row">
            <div class="page-row-left">{{$t('common.base.column.createTime')}}</div>
            <div class="page-row-right">{{part.createTime | fmt_datetime}}</div>
          </div>
          <div class="page-row">
            <div class="page-row-left">{{$t('product.detail.type.id')}}</div>
            <div class="page-row-right">{{part.id}}</div>
          </div>
          <div class="page-row productTypeField" v-if="initData && initData.openSuperCodePro">
            <div class="page-row-left">{{$t('common.form.type.related_catalog')}}</div>
            <div class="page-row-right">
              <div
                :key="item.id"
                v-for="item in productTypeField">
                <el-tooltip
                  class="item"
                  effect="dark"
                  :content="item.pathName"
                  placement="top">
                  <p
                    class="link"
                    @click="openProductMenuTab(item.id)">
                    {{ item.pathName }}
                  </p>
                </el-tooltip>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <div class="page-panel page-main-addition" ref="addition">
        <el-tabs :value="activeTab" @input="switchTab" @tab-click="rightTabClick">
          <el-tab-pane :label="$t('common.form.type.relatedData')" disabled>
             <span slot="label"><i class="el-icon-menu"></i> {{$t('common.form.type.relatedData')}}</span>
          </el-tab-pane>
          
          <el-tab-pane :label="$t('common.base.dynamicInfo')" name="record">            
            <part-record :items="record.data.list"></part-record>

            <div class="part-record-loadmore" v-if="record.data.hasNextPage">
              <el-button type="text" :loading="record.loading" @click="loadMoreRecords">{{record.loading ? $t('common.base.isLoading2') : $t('common.base.tip.loadMore')}}</el-button>
            </div>
          </el-tab-pane>

          <el-tab-pane :label="$t('common.base.usageRecord')" name="usageRecord" v-if="report && isAll">
            <div class="part-use-form">
              <div class="about-num">
                <span>{{$t('part.detail.text3')}}{{usageRecord.data.taskTotalNum}}</span>
                <span>{{$t('part.detail.text4')}}{{usageRecord.data.partTotalNum}}</span>
              </div>               
              <div class="part-use-form-group">
                <!-- <div id="date-range" class="part-use-form-daterange">
                  <span>{{usageRecord.startTime}} - {{usageRecord.endTime}}</span> 
                  <b class="caret"></b>
                </div> -->
                <date-picker @datePicker="datePicker" />
              </div>
            </div>
            
            <part-usage-record :page="usageRecord.data" @changePageNum="changePageNum"></part-usage-record>
          </el-tab-pane>

          <el-tab-pane :label="$t('part.detail.text6')" name="stock">
            <part-stock :stock="stock.data"></part-stock>
          </el-tab-pane>
        </el-tabs> 
      </div>

      <el-dialog :title="$t('common.base.addRemark')" :visible.sync="record.dialog" width="600px">
        <part-remark-form ref="remarkForm" v-if="record.dialog"></part-remark-form>
        <div slot="footer" class="dialog-footer">
          <!--<el-button type="text" @click="record.dialog = false">关 闭</el-button>-->
          <!--<el-button type="primary" @click="createRemark" :disabled="pending">确 定</el-button>-->

          <el-button type="plain-third" @click="record.dialog = false" >{{$t('common.base.close')}}</el-button>
          <el-button type="primary" @click="createRemark" :disabled="pending">{{$t('common.base.makeSure')}}</el-button>

        </div>
      </el-dialog> 

    </div>
   <!-- 通栏弹窗 -->
   <biz-layout-modal
     ref="bizLayoutModal"
     :biz-layout-type="Layout"
     :columns="formCellCount"
     @changeLayout="changeDetailLayout">
   </biz-layout-modal>
  </div>

</template> 

<script>
/*global AMap, moment, _init_data*/
import _ from 'lodash';
import qs from '@src/util/querystring2';
import AuthUtil from '@src/util/auth';
import { getRootWindow } from '@src/util/dom';

import Page from '@src/model/Page';

import PartRecord from './components/PartRecord.vue';
import PartUsageRecord from './components/PartUsageRecord.vue';
import PartStock from './components/PartStock.vue';
import PartRemarkForm from './form/PartRemarkForm.vue';
import SampleTooltip from 'packages/SampleTooltip/SampleTooltip'

/* mixin */
import ThemeMixin from '@src/mixins/themeMixin/index.ts'
/* utils */
import { openAccurateTab } from '@src/util/platform';
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import { objectDateToTimestamp,useStateSystemViewLayout } from 'pub-bbx-utils';
import { t as $t} from '@src/locales'
/* components */
import BaseTileLayoutTabBar2 from '@src/component/common/BaseTabBar/BaseTileLayoutTabBar2.vue';

export default {
  name: 'part-detail-view',
  inject: ['initData'],
  mixins: [ThemeMixin, ThemeMixin],
  data() {
    return {
      activeTab: 'record',
      leftActiveTab: 'leftInfo',
      rightActiveTab: 'record',
      remarkDialog: false,
      pending: false,
      auths: [],

      id: '',
      part: {},

      record: {
        data: new Page(),
        dialog: false,
        loading: false
      },

      stock: {
        init: false,
        data: []
      },

      usageRecord: {
        init: false,
        pageNum: 1,
        startTime:'',
        endTime:'',
        data: {}
      },
      Layout: 2,
      formCellCount: 1,
      tabPosition: '',
      currentTab: {
        tabName: ''
      }
    }
  },
  computed: {
    getLayout() {
      return this.Layout
    },
    leftBarList() {
      return [{
        tabName: this.leftActiveTab,
        disabled: true,
        tabShow: true,
        tabLabel: $t('part.detail.text1'),
        position: 'left'
      }]
    },
    rightBarList() {
      return [{
        tabName: 'relatedData',
        disabled: false,
        tabShow: true,
        tabLabel: $t('common.form.type.relatedData'),
        position: 'left',
        icon: `<i class="el-icon-menu"></i>`
      },{
        tabName: 'record',
        disabled: true,
        tabShow: true,
        tabLabel: $t('common.base.dynamicInfo'),
        position: 'left'
      },{
        tabName: 'usageRecord',
        disabled: true,
        tabShow: true,
        tabLabel: $t('common.base.usageRecord'),
        position: 'left'
      },{
        tabName: 'stock',
        disabled: true,
        tabShow: true,
        tabLabel: $t('part.detail.text6'),
        position: 'left'
      }]
    },
    mergeTabs() {
      return [...this.leftBarList, ...this.rightBarList]
    },
    getformItemClass() {
      return `bbx-form-cell-item-${this.formCellCount}`
    },
    getformItem() {
      return `bbx-cell-form-box-${this.formCellCount}`
    },
    //是有允许编辑备件
    allowEdit(){
      return AuthUtil.hasAuth(this.auths, 'VIP_SPAREPART_EDIT')
    },
    allowDelete(){
      return AuthUtil.hasAuth(this.auths, 'VIP_SPAREPART_DELETE')
    },
    report(){
      return AuthUtil.hasAuth(this.auths, 'VIP_REPORT_VIEW')
    },
    //运营分析是否有全部权限
    isAll(){     
      return this.auths['VIP_REPORT_VIEW'] == 3 
    },
    productTypeField() {
      let data = this.initData?.catalogs
      return data || []
    },
    // 是否开放服务商查看服务项目和物料的价格信息
    serviceProviderShowPrice() {
      try {
        const RootWindow = getRootWindow(window);
        const InitData = RootWindow._init ? JSON.parse(RootWindow._init) : {};
        return InitData.serviceProviderShowPrice ?? true;
      } catch (error) {
        return true;
      }
    }
  },
  methods: {
    async initStock(){
      let loading = this.$loading({
        target: this.$refs.addition
      })

      try {
        let result = await this.$http.get(`/partV2/category/stock/${this.id}`, {});
        if(!Array.isArray(result) || result.length == 0) result = null;
        this.stock.data = result;
        this.stock.init = true;
      } catch (error) {
        console.log(error)
      }

      loading.close();
    },
    async initUsageRecord(){
      let loading = this.$loading({
        target: this.$refs.addition
      })

      let param = {
        primaryId: this.id,
        pageNum: this.usageRecord.pageNum,
        startTime: this.usageRecord.startTime,
        endTime: this.usageRecord.endTime
      };

      objectDateToTimestamp(param, [
        'startTime',
        'endTime',
      ])

      try {
        let result = await this.$http.post(`/partV2/category/logInTask`, param);
        this.usageRecord.data = result;
        this.usageRecord.init = true;
      } catch (error) {
        console.log(error)
      }

      loading.close();
    },
    changePageNum(pageNum) {
      this.usageRecord.pageNum = pageNum;
      this.initUsageRecord();
    },
    initDateRangePicker(start, end) { //时间控件
      // $("#date-range").daterangepicker(
      //   {
      //     startDate: start,
      //     endDate: end,
      //     applyClass: "btn-primary",
      //     opens: "left",
      //     format: "YYYY-MM-DD",
      //     dateLimit: {years: 1},
      //     ranges: {
      //       今天: [moment(), moment()],
      //       昨天: [moment().subtract(1, "days"), moment().subtract(1, "days")],
      //       最近7天: [moment().subtract(6, "days"), moment()],
      //       最近30天: [moment().subtract(29, "days"), moment()],
      //       这个月: [moment().startOf("month"), moment()],
      //       上个月: [
      //         moment().subtract(1, "month").startOf("month"),
      //         moment().subtract(1, "month").endOf("month")
      //       ]
      //     },
      //     locale: {
      //       applyLabel: "确定",
      //       cancelLabel: "取消",
      //       fromLabel: "开始",
      //       toLabel: "结束",
      //       customRangeLabel: "自定义",
      //       daysOfWeek: "日_一_二_三_四_五_六".split("_"),
      //       monthNames: "1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月".split("_")
      //     }
      //   },
      //   this.chooseCategoryDate
      // );
    },
    datePicker(data) {
      this.chooseCategoryDate(data[0], data[1]);
    },
    chooseCategoryDate(start, end){ //选择时间
      this.usageRecord.startTime = start;
      this.usageRecord.endTime = end;
      this.usageRecord.pageNum = 1;
      this.initUsageRecord();
    },
    edit(){
      if(!this.allowEdit) return;
      window.location.href = `${this.$resourcePrefix}/partV2/category/edit?id=${this.id}`
    },
    //删除备件
    async remove(){
      try {
        if(!this.allowEdit) return;
        if(!await this.$platform.confirm(this.$t('part.detail.text7'))) return;

        this.pending = true;
        let result = await this.$http.post('/partV2/category/remove', {id: this.id}, false)
        if(result.status == 0){
          window.location.href = `${this.$resourcePrefix}/partV2/category/list`;
        }else{
          this.$platform.alert(result.message);
        }
      } catch (error) {
        console.log(error)
      }
      this.pending = false;
    },
    //添加备注
    async createRemark(){
      let form = this.$refs.remarkForm;
      if(null == form) return;

      let remark = await form.pack();
      if(null == remark) return;

      this.pending = true;
      try {
        //补全参数
        remark.primaryId = this.id;
        remark.primaryName = this.part.name;

        let result = await this.$http.post('/partV2/category/sRecord/create', remark);
        if(result.status == 0){
          this.record.dialog = false;
          this.initRecords();
        }else{
          this.$platform.alert(result.message);
        }

      } catch (error) {
        console.log(error)
      }
      this.pending = false;
    },
    //备件图片预览
    preview(url,urls){
      this.$previewElementImg(url,urls)
      // let imgs = this.$el.querySelectorAll('.part-image');
      // BaseGallery.preview(event.currentTarget);
    },
    rightTabClick(tab) {
      this.$track.clickStat(this.$track.formatParams('DETAIL_ADD_ONS_TABS', tab.label));
    },
    switchTab(tab){
      this.currentTab.tabName = tab
      if(this.activeTab == tab) return;
      this.activeTab = tab;
      
      if(this.activeTab == 'stock' && !this.stock.init){
        this.initStock();
      }

      if(this.activeTab == 'usageRecord' && !this.usageRecord.init){
        this.initUsageRecord();
      }
    },
    async loadMoreRecords(){
      this.record.loading = true;
      try {
        this.record.data.pageNum += 1;

        let result = await this.fetchRecords();
        result = _.assign(new Page(), result);

        for(let name in this.record.data){
          if(result[name] == undefined) continue;
          else if(name == 'list') this.record.data[name] = this.record.data[name].concat(result[name] || []);
          else this.record.data[name] = result[name];
        }

      } catch (error) {
        console.log(error)
      }
      this.record.loading = false;
    },
    async initRecords(){
      try {
        this.activeTab = 'record';
        let loading = this.$loading({
          target: this.$refs.addition
        })
        
        this.record.data.pageNum = 1;
        let records = await this.fetchRecords();
        this.record.data = Page.as(records);
        loading.close();
      } catch (error) {
        console.log(error)
      }
    },
    async initDetail(){
      try {
        let loading = this.$loading({
          target: this.$refs.detail
        })
        let part = await this.fetchData();
        this.part = part;
        loading.close();
      } catch (error) {
        console.log(error)
      }
    },
    async initialize(){
      try {
        let loading = this.$loading();
        let microTask = [];

        this.record.data.pageNum = 1;
        microTask.push(this.fetchData());
        microTask.push(this.fetchRecords())
         
        let [part, recordData] = await Promise.all(microTask);
        if(part?.imageGroup && part.imageGroup.length !== 0) {
          part.imageGroup.forEach(item => {
            this.$set(item, 'filename', item.fileName)
          })
        }
        this.part = part;
        this.record.data = recordData;
        loading.close();
      } catch (error) {
        console.warn(error)
      }

      // this.initDateRangePicker(start, end);
      // this.usageRecord.startTime = start;
      // this.usageRecord.endTime = end;
    },
    fetchData(){
      return this.$http.get('/partV2/category/get', {id: this.id})
    },
    fetchRecords(){
      let page = this.record.data;

      let params = {
        primaryId: this.id,
        pageNum: page.pageNum,
        pageSize: page.pageSize
      }

      return this.$http.get('/partV2/category/sRecord', params);
    },
    openProductMenuTab(id) {
      let fromId;
      try {
        fromId = window.frameElement.getAttribute('id');
      } catch (error) {
        
      }
      // this.$platform.openTab({
      //   id: `productV2_catalog_view_${id}`,
      //   title: '产品类型详情',
      //   close: true,
      //   url: `/productV2/catalog/view?id=${id}`,
      //   fromId
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.PageProductV2CatalogView,
        key: id,
        params: `id=${id}`,
        fromId
      });
    },

		getBtnsTrackData(id, data) {
			return this.$track.formatParams(id, data, 'DETAIL_BTNS_GROUP')
		},
    baseUpdate(item) {
      this.currentTab = item;
      console.log(this.currentTab)
    },
    openBaseLayoutModal() {
      this.$refs.bizLayoutModal.open()
    },
    changeDetailLayout(type, columns) {
      this.leftActiveTab = this.leftActiveTab 
      this.Layout = type
      this.tabPosition = 'left'
      if(type === 2) {
        this.rightActiveTab = 'record' 
      }
      this.formCellCount = columns * 1
    },
    async initFormBuilderCellCount(){
      const { getSystemViewLayout } = useStateSystemViewLayout()
      const count = await getSystemViewLayout()
      this.Layout = count.baseLayout || 2;
      this.formCellCount = count.formCellCount || 1;
    },
  },
  async mounted(){
    let initData = this.initData;

    this.auths = initData.auths || {};

    let urlParams = qs.parse(window.location.search);
    this.id = urlParams.id;

    // this.$nextTick(() => this.initialize(moment().subtract(6, "days"), moment()));
    this.$nextTick(() => this.initialize());
    this.currentTab = {
      tabName: this.leftActiveTab
    }
    await this.initFormBuilderCellCount()
  },
  components: {
    [PartRecord.name]: PartRecord,
    [PartStock.name]: PartStock,
    [PartUsageRecord.name]: PartUsageRecord,
    [PartRemarkForm.name]: PartRemarkForm,
    [SampleTooltip.name]: SampleTooltip,
    BaseTileLayoutTabBar2
  }
}
</script>

<style lang="scss">
.part-delete{
  float:right;
  color:#f56c6c;
}
.part-image{
  display: block;
  max-width: 128px;
  max-height: 128px;
  cursor: pointer;
}

.part-record-loadmore{
  text-align: center;
}

.part-empty-tip{
  text-align: center;
  padding: 30px 0;
  color: #9a9a9a;
  font-weight: 600;
}
.part-use-form{
  margin:0 10px 0 10px;
  padding-bottom:10px;
  display: flex;
  flex-flow: row nowrap;
  color: #595854;
  border-bottom: 1px solid #ebeef5;
  .about-num{
    flex:1;
    margin-right: 20px;
    font-size: 14px;
    line-height: 26px;
    span{
      margin-right:30px;
    }
  }
  .part-use-form-group {
    display: flex;
    flex-flow: row nowrap;
    // border: 1px solid #d9d9d9;
    border-radius: 2px;
    margin-left: 5px;
    background-color: #fff;
  }

  .part-use-form-daterange{
    height: 24px;
    line-height: 24px;
    width: 200px;
    padding: 0 4px;
    border-radius: 2px;
    background: #fff;
    cursor: pointer;

    span {
      display: inline-block;      
      font-size: 14px;
      font-weight: 400;
      width: calc(100% - 14px);
    }
  }

  label{
    height: 24px;
    line-height: 24px;
    margin: 0;
  }

  input{
    border: none;
    outline: none;
    width: 200px;
    padding: 2px 6px;
  }
}
.category-detail{
  background: #f5f5f5;
  .daterangepicker .ranges {
    width: 180px !important;
  }
  .daterangepicker .input-mini {
    width: 84px !important;
  }
  .daterangepicker .btn-sm {
      font-size: 12px;
      line-height: 1.5;
      padding: 5px 10px;
      border-radius: 3px;
  }
  .daterangepicker .btn-primary {
    color: rgb(255, 255, 255);
    background-color: rgb(51, 122, 183);
    border-color: rgb(46, 109, 164);
  }
  .page-main-addition{
    overflow: hidden;
  }
  .base-timeline {
    padding-left: 0;
  }
  .base-timeline-item {
    border-left: 0px;
  }
}
</style>
<style lang="scss" scoped>
.page-main-detail {
  overflow: auto;
}
.link {
  color: $color-primary-light-6;
  cursor: pointer;
}
.productTypeField {
  .page-row-right {
    overflow: hidden;
    line-height: 1;
    .link {
      text-overflow: ellipsis;
      white-space: nowrap;
      display: inline-block;
      max-width: 100%;
      overflow: hidden;
    }
  }
}
.row-image {
  flex-wrap: nowrap;
  .label-image {
    flex-shrink: 0;
  }
  .content-image {
    overflow-x: hidden;
  }
  .part-image-base {
    ::v-deep .base-file-info-name{
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      display: block;
    }
    ::v-deep span {
      color: $text-color-secondary;
    }
  }
}
.page-main-addition{
  max-width: 50%;
}
</style>
<style lang="scss" scoped>
.page-row-left {
  text-align: left;
}
.page-row.form-view-row {
  .page-row-left {
    width: 98px;
  }
}
.page-main-detail {
  position: relative;
}
.page-panel {
  .sample-tooltip-content {
    padding-left: 0;
  }
  .page-panel-head {
    padding-top: 0;
    padding-bottom: 0;
    border-bottom: 1px solid #E4E7ED;
    box-sizing: border-box;
    h5 {
      position: relative;
      width: fit-content;
      padding: 10px 0 8px;
      margin-left: 10px;
      color: $color-primary-light-6;
      cursor: pointer;
      &::after {
        content: '';
        position: absolute;
        z-index: 1;
        bottom: -1px;
        left: 0;
        height: 2px;
        width: 100%;
        background: $color-primary-light-6;
      }
    }
  }
  ::v-deep .el-tabs__nav-scroll .el-tabs__nav #tab-0 {
    padding-left: 20px;
    
  }
  ::v-deep .el-tabs__header .el-tabs__nav-wrap {
    &::after {
      height: 1px;
      background: #E4E7ED;
    }
  }
}
.detail {
  height: 100%;
  position: relative;
  ::v-deep .el-tab-pane {
    min-height: 474px;
  }
}
.layoutDialog {
  position: absolute;
  right: 0;
  width: fit-content;
  height: 39px;
  align-items: normal;
  background: #ffffff;
  border-bottom: 1px solid #e4e7ed;
  &::after {
    border: none;
  }
}
.layoutDialog2 {
  position: absolute;
}
.detail_h {
  height: 100%;
  background: #ffffff;
}
.page-row {
  .page-row-left {
    &::after {
      content: ":";
      position: relative;
      top: -0.5px;
      margin: 0 8px 0 2px;
      font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial,
      'Noto Sans', sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol',
      'Noto Color Emoji';
    }
  }
}
</style>